<template>
  <el-dialog
    :model-value="yamlIngressDialogVisible"
    title="YAML"
    width="60%"
    @close="handleClose"
  >
    <div ref="yamlEditor" class="ace-editor"></div>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="handleConfirm">更新</el-button>
        <el-button @click="handleClose">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch, onMounted, defineProps, defineEmits } from 'vue';
import requestUtil from '@/util/request';
import { ElMessage } from 'element-plus';
import ace from 'ace-builds/src-noconflict/ace';

// 定义Props
const props = defineProps({
  resource_name: {
    type: String,
    required: true,
    default: '',
  },
  resource_namespace: {
    type: String,
    required: true,
    default: '',
  },
  resource: {
    type: String,
    required: true,
    default: '',
  },
  yamlIngressDialogVisible: {
    type: Boolean,
    required: true,
    default: false,
  },
});

// 定义Ref
const yamlEditor = ref(null);

// 定义Emits
const emits = defineEmits(['update:modelValue']);


// 获取并初始化YAML数据
const initYamlData = async () => {
  try {
    const res = await requestUtil.get(`export_yaml?name=${props.resource_name}&namespace=${props.resource_namespace}&resource=${props.resource}`);
    if (res.data && res.data.data) {
      const editor = ace.edit(yamlEditor.value);
      editor.setValue(res.data.data);
      editor.setTheme('ace/theme/monokai');
      editor.getSession().setMode('ace/mode/yaml');
      editor.setFontSize(15);
      editor.gotoLine(1);
    }
  } catch (error) {
    ElMessage.error('获取YAML数据失败');
  }
};

// 监听打开窗口
watch(() => props.yamlIngressDialogVisible, (newValue) => {
  if (newValue) {
    initYamlData();
  }
});

// 关闭对话框
const handleClose = () => {
  emits('update:modelValue', false);
};

// 确认更新（
const handleConfirm = async () => {
  // 获取编辑器内容
  const editor = ace.edit(yamlEditor.value);
  const updatedYaml = editor.getValue();

  let result = await requestUtil.post("apply_yaml/", {yaml_content:updatedYaml});
  let data = result.data;
  if (data.code === 200) {
    ElMessage.success(data.msg);
  } else {
    ElMessage.error(data.msg);
  }

  // 暂时只关闭对话框
  handleClose();
};


</script>

<style scoped>
.ace-editor {
  width: 100%;
  height: 350px;
  border: 1px solid #ccc;
}
</style>